<script lang="ts" setup>
import type { PerEmployeeApi } from '#/api/per/employee';

import { computed, getCurrentInstance, h, nextTick, ref, watch } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Divider, Menu } from 'ant-design-vue'; // 引入 Divider，移除 Card

import { getCurrentCelebrations } from '#/api/per/businessCelebrations';
import { getCurrentEduExperiences } from '#/api/per/businessEduExperience';
import { getCurrentFamilyEmigration } from '#/api/per/businessFamilyEmigration';
import { getCurrentFamilyEmployment } from '#/api/per/businessFamilyEmployment';
import { getCurrentFamilyMarriage } from '#/api/per/businessFamilyMarriage';
import { getCurrentFamilyMember } from '#/api/per/businessFamilyMember';
import { getCurrentFamilyOperation } from '#/api/per/businessFamilyOperation';
import { getCurrentFamilyStudy } from '#/api/per/businessFamilyStudy';
import { getCurrentFamilySupervisor } from '#/api/per/businessFamilySupervisor';
import { getCurrentPositionExperiences } from '#/api/per/businessPositionExperience';
import { getCurrentPostExperiences } from '#/api/per/businessPostExperience';
import { getCurrentWorkExperiences } from '#/api/per/businessWorkExperience';
import { getEmployee } from '#/api/per/employee';

import CelebrationsList from '../../components/celebrations/celebrationsList.vue';
import EduExperienceList from '../../components/eduExperience/eduExperienceList.vue';
import EmployeeDetail from '../../components/employee/employeeDetail.vue';
import FamilyEmigrationList from '../../components/familyEmigration/familyEmigrationList.vue';
import FamilyEmploymentList from '../../components/familyEmployment/familyEmploymentList.vue';
import FamilyMarriageList from '../../components/familyMarriage/familyMarriageList.vue';
import FamilyMemberList from '../../components/familyMember/familyMemberList.vue';
import FamilyOperationList from '../../components/familyOperation/familyOperationList.vue';
import FamilyStudyList from '../../components/familyStudy/familyStudyList.vue';
import FamilySupervisorList from '../../components/familySupervisor/familySupervisorList.vue';
import PositionExperienceList from '../../components/positionExperience/positionExperienceList.vue';
import PostExperienceList from '../../components/postExperience/postExperienceList.vue';
import WorkExperienceList from '../../components/workExperience/workExperienceList.vue';

// -----------------------------
// Props
// -----------------------------
const props = defineProps<{
  showCancelButton?: boolean;
  showConfirmButton?: boolean;
  title?: string;
}>();

const modalTitle = props.title || '人员综合信息';
const showCancel =
  props.showCancelButton === undefined ? true : props.showCancelButton;
const showConfirm =
  props.showConfirmButton === undefined ? false : props.showConfirmButton;

// -----------------------------
// 状态
// -----------------------------
const formData = ref<PerEmployeeApi.Employee | undefined>(undefined);
const EmployeeFormData = ref<PerEmployeeApi.Employee | undefined>(undefined);
const employeeId = ref<number | undefined>(undefined);

// 右侧列表数据
const familyMembers = ref<any[]>([]);
const familyEmployments = ref<any[]>([]);
const familyStudies = ref<any[]>([]);
const familyEmigrations = ref<any[]>([]);
const familyMarriages = ref<any[]>([]);
const familyOperations = ref<any[]>([]);
const familySupervisors = ref<any[]>([]);
const celebrations = ref<any[]>([]);

// 各类“当前”经历表单数据
const EduExperienceFormData = ref<any[]>([]);
const WorkExperienceFormData = ref<any[]>([]);
const PositionExperienceFormData = ref<any[]>([]);
const PostExperienceFormData = ref<any[]>([]);

// 导航状态
const activeCategory = ref<string>('basic');
const activeAnchor = ref<string>('base-info');
const openCategory = ref<string>('basic');
const scrollContainerRef = ref<HTMLElement | null>(null); // 滚动容器的 ref

// -----------------------------
// 大类 & 小类 配置
// -----------------------------
const categories = [
  { key: 'basic', label: '个人基础信息' },
  { key: 'family', label: '家庭和社会关系' },
  { key: 'assets', label: '资产与收入' },
  { key: 'honor', label: '荣誉' },
  { key: 'foreign', label: '涉外相关' },
  { key: 'other', label: '其他' },
];

const subItems: Record<string, Array<{ id: string; label: string }>> = {
  basic: [
    { id: 'base-info', label: '基本信息' },
    { id: 'edu-info', label: '教育经历' },
    { id: 'work-info', label: '工作经历' },
    { id: 'post-info', label: '任职经历' },
    { id: 'tech-post-info', label: '专业技术岗位' },
  ],
  family: [
    { id: 'family-member', label: '家庭成员' },
    { id: 'employment', label: '从业情况' },
    { id: 'study', label: '求学情况' },
    { id: 'emigration', label: '移居国外情况' },
    { id: 'foreign-marriage', label: '外国人通婚' },
    { id: 'business', label: '从业及从事经营活动情况' },
    { id: 'supervisor', label: '境内主管' },
    { id: 'celebration', label: '婚丧喜庆' },
  ],
  assets: [
    { id: 'salary', label: '工资情况' },
    { id: 'house', label: '房产情况' },
    { id: 'car', label: '车辆情况' },
    { id: 'finance', label: '金融理财' },
    { id: 'insurance', label: '投资型保险' },
    { id: 'stock', label: '股票情况' },
    { id: 'fund', label: '基金情况' },
    { id: 'business-income', label: '经商办企业' },
    { id: 'labor', label: '劳务所得情况' },
    { id: 'parttime', label: '兼职情况' },
    { id: 'overseas-deposit', label: '国境外存款' },
    { id: 'overseas-invest', label: '国境外投资' },
  ],
  honor: [
    { id: 'honor-all', label: '综合荣誉' },
    { id: 'honor-other', label: '其他荣誉' },
  ],
  foreign: [
    { id: 'exit', label: '出国情况' },
    { id: 'passport', label: '出国证件' },
  ],
  other: [
    { id: 'criminal', label: '刑事情况' },
    { id: 'shape1', label: '第一形态' },
    { id: 'unit-car', label: '单位用车情况' },
  ],
};

// 计算当前显示的子项目列表，避免在模板中写大量 v-if/v-else-if
const currentSubItems = computed(() => {
  return subItems[activeCategory.value] || [];
});

// -----------------------------
// 组件映射
// -----------------------------
const componentNameMap: Record<string, string> = {
  // basic
  'basic:基本信息': 'EmployeeDetail',
  'basic:教育经历': 'EduExperienceList',
  'basic:工作经历': 'WorkExperienceList',
  'basic:任职经历': 'PositionExperienceList',
  'basic:专业技术岗位': 'PostExperienceList',

  // family
  'family:家庭成员': 'FamilyMemberList',
  'family:从业情况': 'FamilyEmploymentList',
  'family:求学情况': 'FamilyStudyList',
  'family:移居国外情况': 'FamilyEmigrationList',
  'family:外国人通婚': 'FamilyMarriageList',
  'family:从业及从事经营活动情况': 'FamilyOperationList',
  'family:境内主管': 'FamilySupervisorList',
  'family:婚丧喜庆': 'CelebrationsList',

  // assets
  'assets:工资情况': 'SalaryList',
  'assets:房产情况': 'HouseList',
  'assets:车辆情况': 'CarList',
  'assets:金融理财': 'FinanceList',
  'assets:投资型保险': 'InsuranceList',
  'assets:股票情况': 'StockList',
  'assets:基金情况': 'FundList',
  'assets:经商办企业': 'BusinessList',
  'assets:劳务所得情况': 'LaborList',
  'assets:兼职情况': 'ParttimeList',
  'assets:国境外存款': 'OverseasDepositList',
  'assets:国境外投资': 'OverseasInvestList',

  // honor
  'honor:综合荣誉': 'HonorFullList',
  'honor:其他荣誉': 'HonorOtherList',

  // foreign
  'foreign:出国情况': 'GoAbroadList',
  'foreign:出国证件': 'PassportList',

  // other
  'other:刑事情况': 'CriminalList',
  'other:第一形态': 'FirstFormList',
  'other:单位用车情况': 'UnitCarList',
};

const instance = getCurrentInstance();
// 注册组件
instance?.appContext.app.component('EmployeeDetail', EmployeeDetail);
instance?.appContext.app.component('WorkExperienceList', WorkExperienceList);
instance?.appContext.app.component(
  'PositionExperienceList',
  PositionExperienceList,
);
instance?.appContext.app.component('EduExperienceList', EduExperienceList);
instance?.appContext.app.component('PostExperienceList', PostExperienceList);
instance?.appContext.app.component('FamilyMemberList', FamilyMemberList);
instance?.appContext.app.component(
  'FamilyEmploymentList',
  FamilyEmploymentList,
);
instance?.appContext.app.component('FamilyStudyList', FamilyStudyList);
instance?.appContext.app.component(
  'FamilyEmigrationList',
  FamilyEmigrationList,
);
instance?.appContext.app.component('FamilyMarriageList', FamilyMarriageList);
instance?.appContext.app.component('FamilyOperationList', FamilyOperationList);
instance?.appContext.app.component(
  'FamilySupervisorList',
  FamilySupervisorList,
);
instance?.appContext.app.component('CelebrationsList', CelebrationsList);

function resolveComponent(name: string | undefined) {
  if (!name) return EmptyModule;
  const appComponents = instance?.appContext?.components || {};
  if (appComponents[name]) return appComponents[name];

  const alt = [
    name,
    `v-${name}`,
    name.replaceAll(/([A-Z])/g, '-$1').toLowerCase(),
  ];
  for (const n of alt) {
    if (appComponents[n]) return appComponents[n];
  }
  return EmptyModule;
}

function getComponentName(category: string, label: string) {
  return componentNameMap[`${category}:${label}`] || undefined;
}

function getPropName(componentName: string | undefined, id: string) {
  if (id === 'base-info') return 'data';
  if (componentName && componentName.endsWith('List')) return 'list-data';
  return 'data';
}

function getDataFor(id: string) {
  switch (id) {
    case 'base-info': {
      return EmployeeFormData.value;
    }
    case 'business': {
      return familyOperations.value;
    }
    case 'celebration': {
      return celebrations.value;
    }
    case 'edu-info': {
      return EduExperienceFormData.value;
    }
    case 'emigration': {
      return familyEmigrations.value;
    }
    case 'employment': {
      return familyEmployments.value;
    }
    case 'family-member': {
      return familyMembers.value;
    }
    case 'foreign-marriage': {
      return familyMarriages.value;
    }
    case 'post-info': {
      return PositionExperienceFormData.value;
    }
    case 'study': {
      return familyStudies.value;
    }
    case 'supervisor': {
      return familySupervisors.value;
    }
    case 'tech-post-info': {
      return PostExperienceFormData.value;
    }
    case 'work-info': {
      return WorkExperienceFormData.value;
    }
    default: {
      return undefined;
    }
  }
}

// -----------------------------
// Modal 生命周期 & 数据加载
// -----------------------------
const [Modal, modalApi] = useVbenModal({
  async onOpenChange(open: boolean) {
    if (!open) {
      resetState();
      return;
    }
    const data = modalApi.getData<PerEmployeeApi.Employee>();
    if (!data || !data.id) return;
    await initModal(data.id);
  },
});

async function initModal(id: number) {
  employeeId.value = id;
  modalApi.lock();
  try {
    await loadEmployee(id);
    await Promise.all([
      tryLoadApi(
        getCurrentEduExperiences,
        (res) => (EduExperienceFormData.value = res || []),
      ),
      tryLoadApi(
        getCurrentWorkExperiences,
        (res) => (WorkExperienceFormData.value = res || []),
      ),
      tryLoadApi(
        getCurrentPositionExperiences,
        (res) => (PositionExperienceFormData.value = res || []),
      ),
      tryLoadApi(
        getCurrentPostExperiences,
        (res) => (PostExperienceFormData.value = res || []),
      ),
    ]);
  } finally {
    modalApi.unlock();
  }
}

async function loadEmployee(id: number) {
  try {
    const emp = await getEmployee(id);
    formData.value = emp;
    EmployeeFormData.value = emp;

    familyMembers.value = emp.familyMembers || [];
    familyEmployments.value = emp.familyEmployments || [];
    familyStudies.value = emp.familyStudies || [];
    familyEmigrations.value = emp.familyEmigrations || [];
    familyMarriages.value = emp.familyMarriages || [];
    familyOperations.value = emp.familyOperations || [];
    familySupervisors.value = emp.familySupervisors || [];
    celebrations.value = emp.celebrations || [];
  } catch (error) {
    console.error('loadEmployee error', error);
  }
}

async function tryLoadApi(api: any, cb: (v: any) => void) {
  if (!api) return;
  try {
    const res = await api({ employeeId: employeeId.value });
    cb(res);
  } catch (error) {
    console.warn('api load fail', error);
  }
}

// -----------------------------
// 分类切换与锚点滚动
// -----------------------------
async function handleCategoryChange(key: string) {
  // 如果已经是当前分类，不做处理 (或者根据需求刷新)
  const isSameCategory = activeCategory.value === key;
  activeCategory.value = key;
  openCategory.value = key;

  if (!isSameCategory) {
    const first = subItems[key]?.[0]?.id;
    if (first) {
      // 切换大类后，默认滚动到第一个
      await scrollToAnchor(first);
    }
  }

  // 数据加载逻辑
  if (key === 'basic' && employeeId.value) {
    await initModal(employeeId.value);
  }
  if (key === 'family' && employeeId.value) {
    await Promise.all([
      tryLoadApi(
        getCurrentFamilyMember,
        (res) => (familyMembers.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilyEmployment,
        (res) => (familyEmployments.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilyStudy,
        (res) => (familyStudies.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilyEmigration,
        (res) => (familyEmigrations.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilyMarriage,
        (res) => (familyMarriages.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilyOperation,
        (res) => (familyOperations.value = res || []),
      ),
      tryLoadApi(
        getCurrentFamilySupervisor,
        (res) => (familySupervisors.value = res || []),
      ),
      tryLoadApi(
        getCurrentCelebrations,
        (res) => (celebrations.value = res || []),
      ),
    ]);
  }
}

function handleOpenChange(keys: string[]) {
  if (keys.length > 0) {
    const openedKey = keys[keys.length - 1];
    openCategory.value = openedKey;
    if (openedKey !== activeCategory.value) {
      handleCategoryChange(openedKey);
    }
  } else {
    openCategory.value = activeCategory.value;
  }
}

// 统一处理菜单点击事件（包括锚点点击）
async function handleMenuClick({ key }: { key: string }) {
  // 1. 查找点击的 key 是否是某个小类锚点
  let targetCategory = '';
  for (const catKey in subItems) {
    const items = subItems[catKey];
    if (items.some((item) => item.id === key)) {
      targetCategory = catKey;
      break;
    }
  }

  // 如果点击的是小类（锚点）
  if (targetCategory) {
    // 理论上在手风琴模式下 activeCategory 应该已经是 targetCategory
    // 但为了稳健，如果当前大类不对，先切换过去
    if (activeCategory.value !== targetCategory) {
      await handleCategoryChange(targetCategory);
    }
    // 滚动并设置高亮
    await scrollToAnchor(key);
  } else {
    // 如果点击的是大类本身（部分模式下可能触发），也可以处理
    const isCategory = categories.some((cat) => cat.key === key);
    if (isCategory) {
      handleCategoryChange(key);
    }
  }
}

// 封装滚动逻辑
async function scrollToAnchor(id: string) {
  activeAnchor.value = id;
  // 重要：必须等待 DOM 更新（特别是切换大类导致的 v-if 变化）
  await nextTick();

  const el = document.getElementById(id);
  // 或者使用 querySelector: const el = scrollContainerRef.value?.querySelector(`#${id}`);

  if (el) {
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}

// -----------------------------
// watch
// -----------------------------
watch(formData, (nv) => {
  if (!nv) return;
  familyMembers.value = nv.familyMembers || [];
  familyEmployments.value = nv.familyEmployments || [];
  familyStudies.value = nv.familyStudies || [];
  familyEmigrations.value = nv.familyEmigrations || [];
  familyMarriages.value = nv.familyMarriages || [];
  familyOperations.value = nv.familyOperations || [];
  familySupervisors.value = nv.familySupervisors || [];
  celebrations.value = nv.celebrations || [];
});

watch(activeCategory, (newVal) => {
  openCategory.value = newVal;
});

// -----------------------------
// 重置
// -----------------------------
function resetState() {
  formData.value = undefined;
  EmployeeFormData.value = undefined;
  employeeId.value = undefined;

  familyMembers.value = [];
  familyEmployments.value = [];
  familyStudies.value = [];
  familyEmigrations.value = [];
  familyMarriages.value = [];
  familyOperations.value = [];
  familySupervisors.value = [];
  celebrations.value = [];

  EduExperienceFormData.value = [];
  WorkExperienceFormData.value = [];
  PositionExperienceFormData.value = [];
  PostExperienceFormData.value = [];

  activeCategory.value = 'basic';
  activeAnchor.value = 'base-info';
  openCategory.value = 'basic';
}

// -----------------------------
// 占位组件
// -----------------------------
const EmptyModule = {
  name: 'EmptyModule',
  props: {
    title: { type: String, required: false },
    data: { type: null, required: false },
  },
  setup(props: any) {
    return () =>
      h('div', { class: 'empty-module p-6 text-center text-gray-500' }, [
        h(
          'div',
          { class: 'mb-2 text-sm font-medium' },
          props.title || '占位模块',
        ),
        h(
          'div',
          { class: 'text-xs' },
          '该模块尚未开发或未注册为组件，显示占位数据。',
        ),
        props.data
          ? h(
              'pre',
              {
                style: {
                  marginTop: '8px',
                  textAlign: 'left',
                  maxHeight: '180px',
                  overflow: 'auto',
                },
              },
              JSON.stringify(props.data, null, 2),
            )
          : null,
      ]);
  },
};
</script>

<template>
  <Modal
    :title="modalTitle"
    class="h-[90%] w-[90%]"
    :show-cancel-button="showCancel"
    :show-confirm-button="showConfirm"
  >
    <Page class="h-full">
      <!-- 主体：左侧大类导航 + 右侧内容 -->
      <div class="detail-container flex h-full gap-6">
        <!-- 左侧大类导航 -->
        <div class="category-sidebar pr-4">
          <!-- 修改 1: selected-keys 绑定 activeAnchor，实现点击小类高亮 -->
          <Menu
            :selected-keys="[activeAnchor]"
            :open-keys="[openCategory]"
            mode="inline"
            @click="handleMenuClick"
            @open-change="handleOpenChange"
            class="category-menu"
          >
            <Menu.SubMenu
              v-for="cat in categories"
              :key="cat.key"
              :title="cat.label"
            >
              <!-- 修改 2: 移除 span 上的点击事件，直接使用 Menu.Item -->
              <Menu.Item v-for="item in subItems[cat.key]" :key="item.id">
                {{ item.label }}
              </Menu.Item>
            </Menu.SubMenu>
          </Menu>
        </div>

        <!-- 右侧内容 -->
        <div class="content-area flex-1 overflow-hidden">
          <!-- 这里的 ref="scrollContainerRef" 是修复锚点滚动的关键 -->
          <div
            ref="scrollContainerRef"
            class="h-full overflow-y-auto scroll-smooth pr-2"
          >
            <div class="content-sections">
              <!-- 使用 computed 统一渲染，避免大量 v-if -->
              <section
                v-for="item in currentSubItems"
                :id="item.id"
                :key="item.id"
                class="section mb-8"
              >
                <!-- 使用 Divider 替代 Card -->
                <Divider orientation="left" class="section-divider">
                  <span class="text-base font-bold text-gray-700">
                    {{ item.label }}
                  </span>
                </Divider>

                <div class="section-content pl-2">
                  <component
                    :is="
                      resolveComponent(
                        getComponentName(activeCategory, item.label),
                      )
                    "
                    v-bind="{
                      [getPropName(
                        getComponentName(activeCategory, item.label),
                        item.id,
                      )]: getDataFor(item.id),
                    }"
                  >
                    <EmptyModule :title="item.label" />
                  </component>
                </div>
              </section>
            </div>
          </div>
        </div>
      </div>
    </Page>
  </Modal>
</template>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .detail-container {
    flex-direction: column;
    height: auto;
  }

  .category-sidebar {
    width: 100%;
    height: auto;
    max-height: 200px;
    padding-right: 0;
    margin-bottom: 12px;
    border-right: none;
    border-bottom: 1px solid #f0f0f0;
  }

  .content-area {
    padding: 0;
  }
}

.detail-container {
  display: flex;
  gap: 24px;
  height: 100%;
  padding: 8px 0;
  overflow: hidden;
}

/* 左侧大类导航 */
.category-sidebar {
  flex-shrink: 0;
  width: 250px;
  padding-right: 16px;
  overflow-y: auto;
  border-right: 1px solid #f0f0f0;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  padding: 0 16px;
  overflow: hidden;
}

.content-sections {
  padding-top: 8px;
  padding-bottom: 40px; /* 底部留白，方便最后一个锚点滚动 */
}

.section {
  /* 确保锚点定位时有一定上边距缓冲 */
  scroll-margin-top: 20px;
}

/* 样式微调：Divider 文字 */
.section-divider :deep(.ant-divider-inner-text) {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 占位模块样式 */
.empty-module {
  border: 1px dashed #e6f7ff;
  background: #fbfdff;
  padding: 12px;
  border-radius: 6px;
  color: #666;
  font-size: 13px;
  line-height: 1.6;
  text-align: center;
}

/* 菜单样式 */
.category-menu {
  border: none;
}
</style>
